package com.wyix.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.function.Function;

/**
 * Token工具类，用于生成和验证JWT Token
 */
public class TokenUtils {
    /**
     * 从Token中提取用户名
     */
    public static String extractUsername(String token, String secret) {
        return extractClaim(token, secret, Claims::getSubject);
    }

    /**
     * 从Token中提取过期时间
     */
    public static Date extractExpiration(String token, String secret) {
        return extractClaim(token, secret, Claims::getExpiration);
    }

    /**
     * 从Token中提取声明
     */
    public static <T> T extractClaim(String token, String secret, Function<Claims, T> claimsResolver) {
        final Claims claims = extractAllClaims(token, secret);
        return claimsResolver.apply(claims);
    }

    /**
     * 从Token中提取所有声明
     */
    private static Claims extractAllClaims(String token, String secret) {
        SecretKey key = getSigningKey(secret);
        return Jwts.parserBuilder()
                .setSigningKey(key)
                .build()
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 检查Token是否过期
     */
    private static boolean isTokenExpired(String token, String secret) {
        return extractExpiration(token, secret).before(new Date());
    }

    /**
     * 生成Token
     */
    public static String generateToken(String username, String secret, long expirationMillis, Map<String, Object> claims) {
        SecretKey key = getSigningKey(secret);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(username)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + expirationMillis))
                .signWith(key, SignatureAlgorithm.HS256)
                .compact();
    }

    /**
     * 验证Token
     */
    public static boolean validateToken(String token, String username, String secret) {
        try {
            final String extractedUsername = extractUsername(token, secret);
            return (extractedUsername.equals(username) && !isTokenExpired(token, secret));
        } catch (SignatureException e) {
            throw new RuntimeException("Invalid JWT signature");
        } catch (MalformedJwtException e) {
            throw new RuntimeException("Invalid JWT token");
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("Expired JWT token");
        } catch (UnsupportedJwtException e) {
            throw new RuntimeException("Unsupported JWT token");
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("JWT claims string is empty");
        }
    }

    /**
     * 验证Token格式是否正确
     */
    public static boolean isValidTokenFormat(String token, String secret) {
        try {
            SecretKey key = getSigningKey(secret);
            Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取签名密钥
     */
    private static SecretKey getSigningKey(String secret) {
        byte[] keyBytes = secret.getBytes(StandardCharsets.UTF_8);
        return Keys.hmacShaKeyFor(keyBytes);
    }
}
